import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { getCookie } from '../utils/cookie'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      // 需要登录 方可访问
      isAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/forget',
    name: 'Forget',
    component: () => import('../views/Forget.vue')
  },
  {
    path: '/:checkAll(.*)',
    name: '404',
    component: () => import('../views/404Page.vue')
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 如果前往的页面需要登录 且暂未登录 跳转到登录页面
router.beforeEach((to) => {
  if (to.matched[0].meta.isAuth) {
    let cookie = getCookie()
    console.log('是否已经登录', cookie)
    if (!cookie) {
      router.push('/login')
    }
  }
})
export default router
